﻿using Oracle.DataAccess.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using Wicresoft.UnifyShow.Business;
using Wicresoft.UnifyShow.Business.Models;
using Wicresoft.UnifyShow.BusinessImpl;

namespace Wicresoft.UnifyShow2.Portal.Service
{
    public static class DocumentService
    {
        public static string HasFolder(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

        //是否存在文件
        public static bool HasFile(this HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0) ? true : false;
        }

        private static char[] constantother = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        public static string RandomNumberToName()
        {
            int Length = 12;

            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constantother[rd.Next(10)]);
            }
            string No = newRandom.ToString();
            return No;

        }

        public static void UpLoadRunProcess(string filename, string company, string editor, out string msg)
        {
            var siteid = (int)Enum.Parse(typeof(SiteID), company);
            string path = Convert.ToString(ConfigurationManager.AppSettings["path"]) + filename;
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0 ";

            string _sheet = GetSheetName(path);
            if (_sheet != "DutyInfo")
            {
                msg = "请根据模板上传值班计划！";
            }
            else
            {
                OleDbConnection myConn = new OleDbConnection(strCon);
                myConn.Open();
                string[] Sheet = new string[] { "DutyInfo" };

                for (int n = 0; n < Sheet.Length; n++)
                {
                    DataSet myDataSet = new DataSet();
                    string strSql = "select * from [" + Sheet[n] + "$]";
                    OleDbDataAdapter myCommand = new OleDbDataAdapter(strSql, myConn);
                    myCommand.Fill(myDataSet, "[" + Sheet[n] + "$]");
                    myCommand.Dispose();
                    DataTable DT = myDataSet.Tables["[" + Sheet[n] + "$]"];
                    myConn.Close();

                    if (Sheet[n].ToString() == "DutyInfo")
                    {
                        for (int j = 0; j < DT.Rows.Count; j++)
                        {
                            string _keeper = DT.Rows[j][0].ToString().Replace(" ", "");
                            string _dutyDay = DT.Rows[j][1].ToString();
                            DateTime dt;

                            if (string.IsNullOrEmpty(DT.Rows[j][0].ToString().Replace(" ", ""))) break;

                            if (!DateTime.TryParse(_dutyDay, out dt)) continue;

                            DutyPlanModel duty = new DutyPlanModel()
                            {
                                WatchKeeper = DT.Rows[j][0].ToString().Replace(" ", ""),
                                DutyDay = Convert.ToDateTime(DT.Rows[j][1]),
                                DutyPhone = DT.Rows[j][2].ToString().Replace(" ", ""),
                                CreateTime = DateTime.Now,
                                Submitter = editor,
                                SITEID = siteid
                            };
                            if (duty.DutyDay > DateTime.Now)
                            {
                                var ret = CreateDutyInfo(duty);
                            }
                            else
                            {
                                string _label = "DutyDay overdue! in " + (j + 1).ToString();
                                SysLog.WriteSysLog(_label);
                            }

                        }
                    }
                }
                msg = "导入成功！";
            }
        }

        public static bool CreateDutyInfo(DutyPlanModel model)
        {
            string sqlstr = null;
            OracleDataAccess oda = new OracleDataAccess();
            if (model == null)
                return false;
            if (string.IsNullOrEmpty(model.WatchKeeper))
                return false;

            if (IsExist(model))
            {
                //存在
                sqlstr = "Update Dutyplan Set Watchkeeper=:Watchkeeper,ModifyBy=:Submitter,Dutyphone=:Dutyphone,Createtime=:Createtime Where Dutyday=:Dutyday and Siteid=:Siteid";
            }
            else
            {
                //不存在
                sqlstr = "insert into Dutyplan(Dutyday,Watchkeeper,Siteid,Createtime,Submitter,Dutyphone)values(:Dutyday,:Watchkeeper,:Siteid,:Createtime,:Submitter,:Dutyphone)";
            }

            OracleParameter[] commandParameters = new OracleParameter[] { 
                new OracleParameter("Dutyday",model.DutyDay),
                new OracleParameter("Watchkeeper",model.WatchKeeper),
                new OracleParameter("Siteid",model.SITEID),
                new OracleParameter("Createtime",model.CreateTime),
                new OracleParameter("Submitter",model.Submitter),
                new OracleParameter("Dutyphone",model.DutyPhone)
            };
            try
            {
                oda.ExecuteCommand(sqlstr, commandParameters);
                return true;
            }
            catch (Exception ex)
            {
                SysLog.WriteSysLog(ex.ToString());
                return false;
            }

        }

        public static bool IsExist(DutyPlanModel model)
        {
            OracleDataAccess oda = new OracleDataAccess();
            string sqlstr = "Select Watchkeeper,Dutyday,Siteid From Dutyplan where Siteid=:Siteid and to_char(Dutyday, 'yyyy-mm-dd')=to_char(:Dutyday, 'yyyy-mm-dd')";
            OracleParameter[] commandParameters = new OracleParameter[] {
                new OracleParameter("Dutyday",model.DutyDay),
                new OracleParameter("Siteid",model.SITEID)
            };
            var ret = oda.ExecuteReader(sqlstr, commandParameters);
            if (ret.HasRows)
                return true;
            else
                return false;
        }

        public static string GetSheetName(string filePath)
        {
            string sheetName = "";

            System.IO.FileStream tmpStream = File.OpenRead(filePath);
            byte[] fileByte = new byte[tmpStream.Length];
            tmpStream.Read(fileByte, 0, fileByte.Length);
            tmpStream.Close();

            byte[] tmpByte = new byte[]{Convert.ToByte(11),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),
           Convert.ToByte(11),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),
           Convert.ToByte(30),Convert.ToByte(16),Convert.ToByte(0),Convert.ToByte(0)};

            int index = GetSheetIndex(fileByte, tmpByte);
            if (index > -1)
            {

                index += 16 + 12;
                System.Collections.ArrayList sheetNameList = new System.Collections.ArrayList();

                for (int i = index; i < fileByte.Length - 1; i++)
                {
                    byte temp = fileByte[i];
                    if (temp != Convert.ToByte(0))
                        sheetNameList.Add(temp);
                    else
                        break;
                }
                byte[] sheetNameByte = new byte[sheetNameList.Count];
                for (int i = 0; i < sheetNameList.Count; i++)
                    sheetNameByte[i] = Convert.ToByte(sheetNameList[i]);

                sheetName = System.Text.Encoding.Default.GetString(sheetNameByte);
            }
            return sheetName;
        }

        private static int GetSheetIndex(byte[] FindTarget, byte[] FindItem)
        {
            int index = -1;

            int FindItemLength = FindItem.Length;
            if (FindItemLength < 1) return -1;
            int FindTargetLength = FindTarget.Length;
            if ((FindTargetLength - 1) < FindItemLength) return -1;

            for (int i = FindTargetLength - FindItemLength - 1; i > -1; i--)
            {
                System.Collections.ArrayList tmpList = new System.Collections.ArrayList();
                int find = 0;
                for (int j = 0; j < FindItemLength; j++)
                {
                    if (FindTarget[i + j] == FindItem[j]) find += 1;
                }
                if (find == FindItemLength)
                {
                    index = i;
                    break;
                }
            }
            return index;
        }

    }
}